package com.gin.no_gay_alliance.adpter.history;

import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.activity.ReplyHistoryTopicActivity;
import com.gin.no_gay_alliance.activity.TopicReadActivity;
import com.gin.no_gay_alliance.adpter.base.BaseBindingRecyclerViewAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.database.dao.ScanTaskDao;
import com.gin.no_gay_alliance.database.entity.ScanTask;
import com.gin.no_gay_alliance.databinding.DialogScanTaskBinding;
import com.gin.no_gay_alliance.databinding.ItemScanTaskBinding;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;
import com.gin.no_gay_alliance.worker.ScanTaskWorker;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

/**
 * 扫描任务适配器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/21 10:14
 **/
public class ScanTaskAdapter extends BaseBindingRecyclerViewAdapter<ItemScanTaskBinding, ScanTask> implements View.OnClickListener {
    /**
     * 判定为开始状态的状态
     */
    public static final ArrayList<ScanTask.Status> STARTED_ABLE_STATUS = new ArrayList<>(Arrays.asList(ScanTask.Status.IN_PROGRESS, ScanTask.Status.WAITING));

    public ScanTaskAdapter(Context context) {
        super(context);
    }

    public ScanTaskAdapter(@NonNull Context context, @NonNull List<ScanTask> data) {
        super(context, data);
    }

    /**
     * 绑定数据
     *
     * @param holder
     * @param b        绑定对象
     * @param position 位置
     * @param item
     */
    @Override
    protected void onBindViewHolder(ViewHolder<ItemScanTaskBinding> holder, @NonNull ItemScanTaskBinding b, int position, ScanTask item) {
        // 标题
        b.tvTitle.setText(item.title);
        // 状态
        b.tvStatus.setText(item.status.name);
        // 描述
        b.tvDescription.setText(item.description);
        // 进度
        String progress = String.format(Locale.CHINA, "进度: %d / %d, 总页数: %d", item.pageStart, item.pageEnd != null ? item.pageEnd : item.totalPage, item.totalPage);
        b.tvProgress.setText(progress);

        ViewUtils.setGone(!item.watching, b.tagWatching);

        ViewUtils.setGone(STARTED_ABLE_STATUS.contains(item.status), b.ivStart);
        ViewUtils.setGone(!STARTED_ABLE_STATUS.contains(item.status), b.ivPause);

        // 底部按钮
        View[] views = {b.ivPause, b.ivStart, b.layoutParent, b.ivEdit, b.ivDelete, b.ivOpenTopic};
        ViewUtils.setTag(item, views);
        ViewUtils.setOnClickListener(this, views);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        ScanTask item = (ScanTask) v.getTag();
        ScanTaskDao dao = MyApplication.app.ngaDatabase.scanTaskDao();

        // 点击item 浏览模式打开
        if (v.getId() == R.id.layout_parent) {
            ReplyHistoryTopicActivity.startActivity(context, item.topicId, item.title);
        }
        // 打开原帖
        if (v.getId() == R.id.iv_open_topic) {
            TopicReadActivity.startActivity(context, null, item.topicId, 1, 1);
        }
        // 开始任务
        if (v.getId() == R.id.iv_start) {
            item.status = ScanTask.Status.WAITING;
            dao.update(item);
            notifyItemChanged(data.indexOf(item));
            ScanTaskWorker.startWorker();
        }
        // 暂停任务
        if (v.getId() == R.id.iv_pause) {
            item.status = ScanTask.Status.PAUSED;
            dao.update(item);
            notifyItemChanged(data.indexOf(item));
        }
        // 删除任务
        if (v.getId() == R.id.iv_delete) {
            int position = data.indexOf(item);
            AlertDialogUtils.showConfirm(context, "删除扫描任务", "即将删除任务 " + item.title, (d, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    dao.delete(item);
                    data.remove(position);
                    notifyItemRemoved(position);
                }
            });
        }
        // 编辑任务
        if (v.getId() == R.id.iv_edit) {
            DialogScanTaskBinding b = MyApplication.app.managerFactory.getViewBindingManager().getDialogView(DialogScanTaskBinding.class, context);
            b.etTitle.setText(item.title);
            b.etPageStart.setText(String.valueOf(item.pageStart));
            b.etPageEnd.setText(item.pageEnd != null ? String.valueOf(item.pageEnd) : "");
            b.swWatching.setChecked(item.watching);

            AlertDialog dialog = AlertDialogUtils.showConfirm(context, "修改扫描任务", null, b.getRoot(), (d, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    item.title = b.etTitle.getText().toString();
                    item.pageStart = Integer.parseInt(b.etPageStart.getText().toString());

                    String endString = b.etPageEnd.getText().toString();
                    item.pageEnd = !ObjectUtils.isEmpty(endString) ? Integer.valueOf(endString) : null;
                    item.watching = b.swWatching.isChecked();

                    dao.update(item);
                    notifyItemChanged(data.indexOf(item));
                    MyApplication.app.handler.toast("修改成功");
                }
            });

            // 确定按钮
            Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            // 参数校验
            TextWatcher watcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (ObjectUtils.isEmpty(b.etTitle.getText().toString())) {
                        button.setEnabled(false);
                    } else button.setEnabled(!ObjectUtils.isEmpty(b.etPageStart.getText().toString()));
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            };
            b.etTitle.addTextChangedListener(watcher);
            b.etPageStart.addTextChangedListener(watcher);
            b.etPageEnd.addTextChangedListener(watcher);

        }


    }
}
